How to get an enum value from a string value in Java?
How to get an enum value from a string value in C#?
560
21-Aug-2023
Aryan Kumar
23-Aug-2023Sure, here are two ways to get an enum value from a string value in C#:
Enum.Parse()method:C#
In this example, the
myStringvariable is a string that has the value of"Value1". TheMyEnumenum has three values:Value1,Value2, andValue3. TheEnum.Parse(typeof(MyEnum), myString)method casts themyStringvariable to an enum.TryParse()method:C#
In this example, the
myStringvariable is a string that has the value of"Value1". TheMyEnumenum has three values:Value1,Value2, andValue3. TheEnum.TryParse(myString, out MyEnum myEnum)method tries to cast themyStringvariable to an enum. If the conversion is successful, then thesuccessvariable is set totrueand themyEnumvariable is set to the enum value. Otherwise, thesuccessvariable is set tofalseand themyEnumvariable is not modified.Which method you use depends on your specific needs. If you need to get the enum value and you don't need to do any further processing on the enum value, then the
Enum.Parse()method is a good option. If you need to do further processing on the enum value, then theTryParse()method is a good option.